package com.ruoyi.xxljob.admin.controller;

import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.xxljob.admin.core.model.XxlJobGroup;
import com.ruoyi.xxljob.admin.core.model.XxlJobRegistry;
import com.ruoyi.xxljob.admin.core.util.I18nUtil;
import com.ruoyi.xxljob.admin.dao.XxlJobGroupDao;
import com.ruoyi.xxljob.admin.dao.XxlJobInfoDao;
import com.ruoyi.xxljob.admin.dao.XxlJobRegistryDao;
import com.ruoyi.xxljob.core.enums.RegistryConfig;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * job group controller
 * 执行器相关
 *
 * @author wjialong
 */
@RestController
@RequestMapping("/group")
public class JobGroupController extends BaseController {

    @Resource
    public XxlJobInfoDao xxlJobInfoDao;
    @Resource
    public XxlJobGroupDao xxlJobGroupDao;
    @Resource
    private XxlJobRegistryDao xxlJobRegistryDao;


    /**
     * 获取执行器的分页数据
     *
     * @param xxlJobGroup
     * @return
     */
    @RequiresPermissions("xxl-job:group:query")
    @GetMapping("/list")
    public TableDataInfo list(XxlJobGroup xxlJobGroup) {
        startPage();
        List<XxlJobGroup> list = xxlJobGroupDao.pageList(0, 0,
                xxlJobGroup.getAppName(), xxlJobGroup.getTitle());
        return getDataTable(list);
    }

    /**
     * 新增执行器
     *
     * @param xxlJobGroup
     * @return
     */
    @RequiresPermissions("xxl-job:group:add")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody XxlJobGroup xxlJobGroup) {
        // valid
        if (xxlJobGroup.getAppName() == null || xxlJobGroup.getAppName().trim().length() == 0) {
            return AjaxResult.error(500, (I18nUtil.getString("system_please_input") + "AppName"));
        }
        if (xxlJobGroup.getAppName().length() < 4 || xxlJobGroup.getAppName().length() > 64) {
            return AjaxResult.error(500, I18nUtil.getString("jobgroup_field_appname_length"));
        }
        if (xxlJobGroup.getAppName().contains(">") || xxlJobGroup.getAppName().contains("<")) {
            return AjaxResult.error(500, "AppName" + I18nUtil.getString("system_unvalid"));
        }
        if (xxlJobGroup.getTitle() == null || xxlJobGroup.getTitle().trim().length() == 0) {
            return AjaxResult.error(500, (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobgroup_field_title")));
        }
        if (xxlJobGroup.getTitle().contains(">") || xxlJobGroup.getTitle().contains("<")) {
            return AjaxResult.error(500, I18nUtil.getString("jobgroup_field_title") + I18nUtil.getString("system_unvalid"));
        }
        if (xxlJobGroup.getAddressType() != 0) {
            if (xxlJobGroup.getAddressList() == null || xxlJobGroup.getAddressList().trim().length() == 0) {
                return AjaxResult.error(500, I18nUtil.getString("jobgroup_field_addressType_limit"));
            }
            if (xxlJobGroup.getAddressList().contains(">") || xxlJobGroup.getAddressList().contains("<")) {
                return AjaxResult.error(500, I18nUtil.getString("jobgroup_field_registryList") + I18nUtil.getString("system_unvalid"));
            }

            String[] addresss = xxlJobGroup.getAddressList().split(",");
            for (String item : addresss) {
                if (item == null || item.trim().length() == 0) {
                    return AjaxResult.error(500, I18nUtil.getString("jobgroup_field_registryList_unvalid"));
                }
            }
        }

        // process
        xxlJobGroup.setUpdateTime(new Date());

        int ret = xxlJobGroupDao.save(xxlJobGroup);
        return (ret > 0) ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 编辑执行器数据
     *
     * @param xxlJobGroup
     * @return
     */
    @RequiresPermissions("xxl-job:group:edit")
    @PutMapping
    public AjaxResult update(@RequestBody XxlJobGroup xxlJobGroup) {
        // valid
        if (xxlJobGroup.getAppName() == null || xxlJobGroup.getAppName().trim().length() == 0) {
            return AjaxResult.error(500, (I18nUtil.getString("system_please_input") + "AppName"));
        }
        if (xxlJobGroup.getAppName().length() < 4 || xxlJobGroup.getAppName().length() > 64) {
            return AjaxResult.error(500, I18nUtil.getString("jobgroup_field_appname_length"));
        }
        if (xxlJobGroup.getTitle() == null || xxlJobGroup.getTitle().trim().length() == 0) {
            return AjaxResult.error(500, (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobgroup_field_title")));
        }
        if (xxlJobGroup.getAddressType() == 0) {
            // 0=自动注册
            List<String> registryList = findRegistryByAppName(xxlJobGroup.getAppName());
            String addressListStr = null;
            if (registryList != null && !registryList.isEmpty()) {
                Collections.sort(registryList);
                addressListStr = "";
                for (String item : registryList) {
                    addressListStr += item + ",";
                }
                addressListStr = addressListStr.substring(0, addressListStr.length() - 1);
            }
            xxlJobGroup.setAddressList(addressListStr);
        } else {
            // 1=手动录入
            if (xxlJobGroup.getAddressList() == null || xxlJobGroup.getAddressList().trim().length() == 0) {
                return AjaxResult.error(500, I18nUtil.getString("jobgroup_field_addressType_limit"));
            }
            String[] addresss = xxlJobGroup.getAddressList().split(",");
            for (String item : addresss) {
                if (item == null || item.trim().length() == 0) {
                    return AjaxResult.error(500, I18nUtil.getString("jobgroup_field_registryList_unvalid"));
                }
            }
        }

        // process
        xxlJobGroup.setUpdateTime(new Date());

        int ret = xxlJobGroupDao.update(xxlJobGroup);
        return (ret > 0) ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 查找调度中心的注册列表
     *
     * @param appnameParam
     * @return
     */
    private List<String> findRegistryByAppName(String appnameParam) {
        HashMap<String, List<String>> appAddressMap = new HashMap<String, List<String>>();
        List<XxlJobRegistry> list = xxlJobRegistryDao.findAll(RegistryConfig.DEAD_TIMEOUT, new Date());
        if (list != null) {
            for (XxlJobRegistry item : list) {
                if (RegistryConfig.RegistType.EXECUTOR.name().equals(item.getRegistryGroup())) {
                    String appname = item.getRegistryKey();
                    List<String> registryList = appAddressMap.get(appname);
                    if (registryList == null) {
                        registryList = new ArrayList<String>();
                    }

                    if (!registryList.contains(item.getRegistryValue())) {
                        registryList.add(item.getRegistryValue());
                    }
                    appAddressMap.put(appname, registryList);
                }
            }
        }
        return appAddressMap.get(appnameParam);
    }

    /**
     * 删除执行器
     *
     * @param id
     * @return
     */
    @RequiresPermissions("xxl-job:group:remove")
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable int id) {

        // valid
        int count = xxlJobInfoDao.pageListCount(0, 10, id, -1, null, null, null);
        if (count > 0) {
            return AjaxResult.error(500, I18nUtil.getString("jobgroup_del_limit_0"));
        }

        List<XxlJobGroup> allList = xxlJobGroupDao.findAll();
        if (allList.size() == 1) {
            return AjaxResult.error(500, I18nUtil.getString("jobgroup_del_limit_1"));
        }

        int ret = xxlJobGroupDao.remove(id);
        return (ret > 0) ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 执行器单个数据
     *
     * @param id
     * @return
     */
    @RequiresPermissions("xxl-job:group:query")
    @GetMapping("/loadById/{id}")
    public AjaxResult loadById(@PathVariable int id) {
        XxlJobGroup jobGroup = xxlJobGroupDao.load(id);
        return jobGroup != null ? AjaxResult.success(jobGroup) : AjaxResult.error();
    }

//    @RequestMapping
//    @PermissionLimit(adminuser = true)
//    public String index(Model model) {
//        return "jobgroup/jobgroup.index";
//    }
//    @RequestMapping("/save")
//    @ResponseBody
//    @PermissionLimit(adminuser = true)
//    public ReturnT<String> save(XxlJobGroup xxlJobGroup) {
//
//        // valid
//        if (xxlJobGroup.getAppName() == null || xxlJobGroup.getAppName().trim().length() == 0) {
//            return new ReturnT<String>(500, (I18nUtil.getString("system_please_input") + "AppName"));
//        }
//        if (xxlJobGroup.getAppName().length() < 4 || xxlJobGroup.getAppName().length() > 64) {
//            return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_appname_length"));
//        }
//        if (xxlJobGroup.getAppName().contains(">") || xxlJobGroup.getAppName().contains("<")) {
//            return new ReturnT<String>(500, "AppName" + I18nUtil.getString("system_unvalid"));
//        }
//        if (xxlJobGroup.getTitle() == null || xxlJobGroup.getTitle().trim().length() == 0) {
//            return new ReturnT<String>(500, (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobgroup_field_title")));
//        }
//        if (xxlJobGroup.getTitle().contains(">") || xxlJobGroup.getTitle().contains("<")) {
//            return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_title") + I18nUtil.getString("system_unvalid"));
//        }
//        if (xxlJobGroup.getAddressType() != 0) {
//            if (xxlJobGroup.getAddressList() == null || xxlJobGroup.getAddressList().trim().length() == 0) {
//                return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_addressType_limit"));
//            }
//            if (xxlJobGroup.getAddressList().contains(">") || xxlJobGroup.getAddressList().contains("<")) {
//                return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_registryList") + I18nUtil.getString("system_unvalid"));
//            }
//
//            String[] addresss = xxlJobGroup.getAddressList().split(",");
//            for (String item : addresss) {
//                if (item == null || item.trim().length() == 0) {
//                    return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_registryList_unvalid"));
//                }
//            }
//        }
//
//        // process
//        xxlJobGroup.setUpdateTime(new Date());
//
//        int ret = xxlJobGroupDao.save(xxlJobGroup);
//        return (ret > 0) ? ReturnT.SUCCESS : ReturnT.FAIL;
//    }

//    @RequestMapping("/update")
//    @ResponseBody
//    @PermissionLimit(adminuser = true)
//    public ReturnT<String> update(XxlJobGroup xxlJobGroup) {
//        // valid
//        if (xxlJobGroup.getAppName() == null || xxlJobGroup.getAppName().trim().length() == 0) {
//            return new ReturnT<String>(500, (I18nUtil.getString("system_please_input") + "AppName"));
//        }
//        if (xxlJobGroup.getAppName().length() < 4 || xxlJobGroup.getAppName().length() > 64) {
//            return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_appname_length"));
//        }
//        if (xxlJobGroup.getTitle() == null || xxlJobGroup.getTitle().trim().length() == 0) {
//            return new ReturnT<String>(500, (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobgroup_field_title")));
//        }
//        if (xxlJobGroup.getAddressType() == 0) {
//            // 0=自动注册
//            List<String> registryList = findRegistryByAppName(xxlJobGroup.getAppName());
//            String addressListStr = null;
//            if (registryList != null && !registryList.isEmpty()) {
//                Collections.sort(registryList);
//                addressListStr = "";
//                for (String item : registryList) {
//                    addressListStr += item + ",";
//                }
//                addressListStr = addressListStr.substring(0, addressListStr.length() - 1);
//            }
//            xxlJobGroup.setAddressList(addressListStr);
//        } else {
//            // 1=手动录入
//            if (xxlJobGroup.getAddressList() == null || xxlJobGroup.getAddressList().trim().length() == 0) {
//                return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_addressType_limit"));
//            }
//            String[] addresss = xxlJobGroup.getAddressList().split(",");
//            for (String item : addresss) {
//                if (item == null || item.trim().length() == 0) {
//                    return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_registryList_unvalid"));
//                }
//            }
//        }
//
//        // process
//        xxlJobGroup.setUpdateTime(new Date());
//
//        int ret = xxlJobGroupDao.update(xxlJobGroup);
//        return (ret > 0) ? ReturnT.SUCCESS : ReturnT.FAIL;
//    }

//    @RequestMapping("/pageList")
//    @ResponseBody
//    @PermissionLimit(adminuser = true)
//    public Map<String, Object> pageList(HttpServletRequest request,
//                                        @RequestParam(required = false, defaultValue = "0") int start,
//                                        @RequestParam(required = false, defaultValue = "10") int length,
//                                        String appname, String title) {
//
//        // page query
//        List<XxlJobGroup> list = xxlJobGroupDao.pageList(start, length, appname, title);
//        int list_count = xxlJobGroupDao.pageListCount(start, length, appname, title);
//
//        // package result
//        Map<String, Object> maps = new HashMap<String, Object>();
//        maps.put("recordsTotal", list_count);        // 总记录数
//        maps.put("recordsFiltered", list_count);    // 过滤后的总记录数
//        maps.put("data", list);                    // 分页列表
//        return maps;
//    }
}
